package ru.linnenson.darshana.infrastructure.persistence.repositories;

import com.querydsl.core.BooleanBuilder;
import com.querydsl.core.types.Predicate;
import com.querydsl.core.types.dsl.Expressions;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import ru.linnenson.darshana.infrastructure.persistence.models.QMathTaskStore;
import ru.linnenson.darshana.infrastructure.rest.dto.MathTasksCriteria;

import static org.springframework.util.CollectionUtils.isEmpty;

@Component
public class MathTaskPredicateBuilder {

  public Predicate build(final MathTasksCriteria criteria) {

    BooleanBuilder expression = new BooleanBuilder();

    if (!isEmpty(criteria.getSources())) {
      expression.and(QMathTaskStore.mathTaskStore.source.id.in(criteria.getSources()));
    }

    if (!isEmpty(criteria.getNumbersInKim())) {
      expression.and(QMathTaskStore.mathTaskStore.numberInKim.id.in(criteria.getNumbersInKim()));
    }

    if (!isEmpty(criteria.getThemes())) {
      expression.and(QMathTaskStore.mathTaskStore.theme.id.in(criteria.getThemes()));
    }

    if (criteria.isWithSolution()) {
      expression.and(
          Expressions.booleanTemplate("array_length({0}, 1) > 0", QMathTaskStore.mathTaskStore.solutionPhotoIds)
      );
    }

    if (StringUtils.hasText(criteria.getText())) {
      expression.and(QMathTaskStore.mathTaskStore.text.contains(criteria.getText()));
    }

//    if (!CollectionUtils.isEmpty(criteria.getTags())) {
//      expression.and(QMathTaskStore.mathTaskStore.tags.);
//    }

    return expression;
  }
}
